package com.example.coupon.schedule;

import com.example.coupon.dao.CouponTemplateDao;
import com.example.coupon.entity.CouponTemplate;
import com.example.coupon.vo.TemplateRule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时清理已过期的优惠券模版
 *
 * @author wangbo
 * @description:
 * @date 2021/2/1814:38
 */
@Slf4j
@Component
public class ScheduledTask {

    @Resource
    private CouponTemplateDao templateDao;

    /**
     * 下线已过期的优惠券模版
     */
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void offlineCouponTemplate() {
        log.info("Start To Expire CouponTemplate");
        List<CouponTemplate> templates = templateDao.findAllByExpired(false);
        if (CollectionUtils.isEmpty(templates)) {
            log.info("Done To Expire CouponTemplate.");
            return;
        }
        Date cur = new Date();
        List<CouponTemplate> expiredTemplates = new ArrayList<>(templates.size());
        templates.forEach(t->{
            //根据优惠券模版规则中的“过期规则”校验模版是否过期
            TemplateRule rule = t.getRule();
            if (rule.getExpiration().getDeadline() <cur.getTime()){
                t.setExpired(true);
                expiredTemplates.add(t);
            }
        });
        if (CollectionUtils.isNotEmpty(expiredTemplates)){
            log.info("Expired CouponTemplate Num: {}",templateDao.saveAll(expiredTemplates));
        }
        log.info("Done To Expire CouponTemplate.");
    }

}
